package com.commonlib.downloadmgr.base;


import java.util.ArrayList;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

public abstract class DownloadBaseService<T> extends Service {
	public static final String TAG = DownloadBaseService.class.getSimpleName();
	public static final String ACTION_ADD_TO_DOWNLOAD = "action_add_to_download";
	public static final String ACTION_HANDLE_EXCEPTION = "action_handle_exception";
	public static final String EXTRA_DOWNLOADJOB_ID = "extra_downloadjob_id";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate(){
		super.onCreate();
		Log.i(TAG, "DownloadService.onCreate");
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		if(intent == null){
			return;
		}
		String action = intent.getAction();
		Log.i(TAG, "DownloadService.onStart - "+action);
		
		if(ACTION_ADD_TO_DOWNLOAD.equals(action)){
			String jobId =  intent.getStringExtra(EXTRA_DOWNLOADJOB_ID);
			if (jobId == null || TextUtils.isEmpty(jobId)) {
				Log.e(TAG, "can not capture the job id");
				return;
			}
			DownloadBaseJob<T> downloadJob = getDownloadManager(this).getDownloadJob(jobId);
			if (downloadJob == null) {
				Log.e(TAG, "no download job attach to id " + jobId);
				return;
			}
			downloadJob.onStart();
		}else if(ACTION_HANDLE_EXCEPTION.equals(action)){
			//TODO check download database for any not downloaded things, add the to downloadQueue and start
			ArrayList<DownloadBaseJob<T>> activeJobs = getDownloadManager(this).getActiveJobs();
			// previously execute active download job
			if (!activeJobs.isEmpty()) {
				for (DownloadBaseJob<T> job : activeJobs) {
					Log.v(TAG, "reStart cached active job, id: " + job.getId());
					job.onStart();
				}
			// no active job, then push a waiting job into active queue and execute it.
			}else{
				Log.v(TAG, "push a waiting job into active queue");
				getDownloadManager(this).addDownloadJob((getDownloadManager(this).getWaitingJobs().poll()));
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	protected abstract DownloadBaseManager<T> getDownloadManager(Context context);

}

